/*
 *  PIC 18f4550 internal EEPROM routine
 *  Purpose: Read and Write PIC EEPROM
 *
 *  Store variables to be restored after reset
 *
 *  Rolf Ziegler
 *  March 2014
 *  Versio 1.0
 *
 *  Based on microchip datasheet
 *  18f4550 has 256 bytes of EEPROM !!
 */
#include <p18cxxx.h>

/*
MOVLW DATA_EE_ADDR ;
MOVWF EEADR ; Lower bits of Data Memory Address to write
MOVLW DATA_EE_DATA ;
MOVWF EEDATA ; Data Memory Value to write
BCF EECON1, EEPGD ; Point to DATA memory
BCF EECON1, CFGS ; Access EEPROM
BSF EECON1, WREN ; Enable writes
BCF INTCON, GIE ; Disable Interrupts
MOVLW 55h ;
Required MOVWF EECON2 ; Write 55h
Sequence MOVLW 0AAh ;
MOVWF EECON2 ; Write 0AAh
BSF EECON1, WR ; Set WR bit to begin write
BSF INTCON, GIE ; Enable Interrupts
; User code execution
BCF EECON1, WREN ; Disable writes on write complete (EEIF set)
 */

 void EEPROMwrite( unsigned char badd,unsigned char bdata )
 {
     EEADR = (badd & 0x0ff);
     EEDATA = bdata;
     EECON1bits.EEPGD = 0;
     EECON1bits.CFGS = 0;
     EECON1bits.WREN = 1;
     INTCONbits.GIE = 0;
     EECON2 = 0x55;
     EECON2 = 0xAA;
     EECON1bits.WR = 1;

     while(EECON1bits.WR);
     INTCONbits.GIE = 1;
     EECON1bits.WREN = 0;
 }

 /*
MOVLW DATA_EE_ADDR ;
MOVWF EEADR ; Lower bits of Data Memory Address to read
BCF EECON1, EEPGD ; Point to DATA memory
BCF EECON1, CFGS ; Access EEPROM
BSF EECON1, RD ; EEPROM Read
MOVF EEDATA, W ; W = EEDATA
 */

 unsigned char EEPROMread( unsigned char badd )
 {
     EEADR = (badd & 0x0ff);
     EECON1bits.CFGS = 0;
     EECON1bits.EEPGD = 0;
     EECON1bits.RD = 1;
     return ( EEDATA );              // return with read byte
 }


void EEPROMWriteArray(unsigned char eeAddr, void *obj_p, unsigned char objSize)
 {
      unsigned char *p = obj_p;

      while (objSize--) {
          EEPROMwrite(eeAddr++, *p++);
      }
 }

void EEPROMReadArray(unsigned char eeAddr, void *obj_p, unsigned char objSize)
 {
      unsigned char *p = obj_p;

      while (objSize--) {
          *p++ = EEPROMread(eeAddr++);
      }
 }
